package com.eas.biz.framework.dao;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import com.eas.biz.framework.BaseQuery;
import com.ibatis.sqlmap.client.SqlMapClient;

public class GenericDaoImpl<T> extends SqlMapClientDaoSupport {

    @Autowired(required = true)
    public void setSqlMapClientWorkAround(SqlMapClient sqlMapClient) {
        this.setSqlMapClient(sqlMapClient);
    }

    @SuppressWarnings("unchecked")
    protected T selectById(String statementName, long id) {
        Object result = getSqlMapClientTemplate().queryForObject(statementName, id);
        return result != null ? (T) result : null;
    }

    protected long insert(String statementName, T object) {
        Object result = getSqlMapClientTemplate().insert(statementName, object);
        return result != null && (result instanceof Long) ? (Long) result : 0;
    }

    protected int deleteById(String statementName, long id) {
        return getSqlMapClientTemplate().delete(statementName, id);
    }

    protected int update(String statementName, T object) {
        return getSqlMapClientTemplate().update(statementName, object);
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    protected List<T> selectByQuery(String statementName, BaseQuery query) {
        query.formatPagination();
        List result = getSqlMapClientTemplate().queryForList(statementName, query);
        return result != null ? (List<T>) result : new ArrayList<T>();
    }

    protected int countByQuery(String statementName, BaseQuery query) {
        query.formatPagination();
        Object result = getSqlMapClientTemplate().queryForObject(statementName, query);
        return result != null && (result instanceof Integer) ? (Integer) result : 0;
    }

    protected int deleteByQuery(String statementName, BaseQuery query) {
        return getSqlMapClientTemplate().delete(statementName, query);
    }
}
